package com.chen.syn;

// 不安全地买票 ==》安全地买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
       BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "苦逼的我").start();
        new Thread(buyTicket, "牛逼的你们").start();
        new Thread(buyTicket, "可恶的黄牛党").start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNums = 10;
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        // 模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "买了第" + ticketNums-- + "张票");
    }
}
